import Axios from "axios";
import {delStorageItem, getStorageString, setStorageString} from "../utils/localStorage.js";
import {useRouter} from "vue-router";
import router from "../routers/routers.js";

const CodeNoToken = 1201
const CodeAuthenticateError = 1202
const CodeTokenTimeout = 1203


function createClient() {

    const client = Axios.create({
        baseURL: "http://localhost:6785/",
        timeout: 5000,

    })

    client.interceptors.request.use(
        config => {
            config.headers.authorization = getStorageString("token")
            return config
        },
        err => {
            return Promise.reject(err)
        }
    )

    client.interceptors.response.use(
        resp => {
            if (resp.data === undefined) {
                return Promise.reject("no data")
            }
            if (resp.data.status !== 0) {
                return Promise.reject(JSON.stringify(resp.data))
            }
            if (resp.headers.authorization) {
                setStorageString("token", resp.headers.authorization)
            }
            return resp.data
        },
        err => {
            const statusCode = err.response.data.status
            if (statusCode === CodeNoToken ||
                statusCode === CodeAuthenticateError ||
                statusCode === CodeTokenTimeout) {
                delStorageItem("token")
                delStorageItem("userInfo")
                // todo 登出并跳转回首页
                router.push({path: '/login', query: {target: router.currentRoute.value.fullPath}})
                return Promise.reject('登陆超时')
            }
            return Promise.reject(err)
        }
    )
    return client
}

const server = createClient()

export function request(url, config) {
    return server.request({url: url, ...config})
}
